package com.example.sortlistview01.util;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentResolver;
import android.database.Cursor;
import android.provider.ContactsContract;

import com.example.sortlistview01.bean.Contact;

public class QueryContactUtil {
	public static List<Contact> queryContact(ContentResolver resolver,
			Cursor cursor) {
		List<Contact> list = new ArrayList<Contact>();

		if (cursor != null && cursor.getCount() > 0) {
			while (cursor.moveToNext()) {
				int idColumn = cursor
						.getColumnIndex(ContactsContract.Contacts._ID);
				int displayNameColumn = cursor
						.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);

				// 获得联系人的ID号
				String contactId = cursor.getString(idColumn);
				// 获得联系人姓名
				String disPlayName = cursor.getString(displayNameColumn);
				// 查看该联系人有多少个电话号码。如果没有这返回值为0
				int phoneCount = cursor
						.getInt(cursor
								.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
				if (phoneCount > 0) {
					Cursor phonesCursor = resolver.query(
							ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
							null,
							ContactsContract.CommonDataKinds.Phone.CONTACT_ID
									+ " = " + contactId, null, null);
					while (phonesCursor.moveToNext()) {
						// 遍历所有的电话号码
						String phoneNumber = phonesCursor
								.getString(phonesCursor
										.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
						Contact contact = new Contact(contactId, disPlayName,
								phoneNumber);
//						System.out.println(contact.toString());
						list.add(contact);
					}
				}
			}
		}
		cursor.close();
		return list;
	}
}
